package com.timguan.render.dao.manager.cms;

import com.timguan.render.dao.domain.cms.CmsABTestDO;
import com.timguan.render.dao.domain.cms.CmsABTestDOExample;
import com.timguan.render.dao.persistence.cms.CmsABTestDOMapper;

import javax.annotation.Resource;
import java.util.List;

public class CmsABTestManagerImpl {
    @Resource
    private CmsABTestDOMapper cmsABTestDOMapper;
    private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_1 = 20;
    private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_2 = 12;
    private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_3 = 7;
    private static final int DOUG_LEA_BLACK_MAGIC_OPERAND_4 = 4;

    //根据deviceId生成hashcode
    private int getDeviceIdhashCode(String deviceId) {
        int h = deviceId.hashCode();
        h ^= (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_1) ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_2);
        return Math.abs(h ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_3) ^ (h >>> DOUG_LEA_BLACK_MAGIC_OPERAND_4));
    }

    /**
     * 根据条件获取分组
     *
     * @param appId
     * @param appVersion
     * @param srcActivityId
     * @param identify
     * @param devicedId
     */
    public String getGroup(int appId, String appVersion, int srcActivityId, String identify, String devicedId) {
        CmsABTestDOExample cmsABTestDOExample = new CmsABTestDOExample();

        CmsABTestDOExample.Criteria criteria = cmsABTestDOExample.createCriteria();
        criteria.andAppIdEqualTo(appId).andAppVersionEqualTo(appVersion);

        if (srcActivityId != 0) {
            criteria.andSrcActivityIdEqualTo(srcActivityId);
        }
        if (identify != null) {
            criteria.andIdentifyEqualTo(identify);
        }
        List<CmsABTestDO> cmsABTestDOs = selectByExample(cmsABTestDOExample);
        if (cmsABTestDOs != null && cmsABTestDOs.size() > 0) {
            if (cmsABTestDOs.size() == 1) {
                return cmsABTestDOs.get(0).getGroupName();
            }
            int totalPercent = 0;
            for (CmsABTestDO cmsABTestDO : cmsABTestDOs) {
                totalPercent += cmsABTestDO.getPercent();
            }

            int percent = getDeviceIdhashCode(devicedId) % totalPercent;

            int temp = 0;
            for (CmsABTestDO cmsABTestDO : cmsABTestDOs) {
                temp += cmsABTestDO.getPercent();
                if (temp >= percent) {
                    return cmsABTestDO.getGroupName();
                }
            }

            return cmsABTestDOs.get(cmsABTestDOs.size() - 1).getGroupName();
        }

        return null;
    }

    public List<CmsABTestDO> selectByExample(CmsABTestDOExample condition) {
        List<CmsABTestDO> cmsABTestDOs = null;
        if (condition == null) {
            return null;
        }
        cmsABTestDOs = cmsABTestDOMapper.selectByExample(condition);
        return cmsABTestDOs;
    }
}
